# "C:\Program Files\Google\google_appengine\dev_appserver.py" "D:\TalkTalk\piecesofuk\jewel-games"
# "C:\Program Files\Google\google_appengine\appcfg.py" update "D:\TalkTalk\piecesofuk\jewel-games"
import cgi
import os
import logging
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from django.utils import simplejson

class Hiscore(db.Model):
  game = db.StringProperty(multiline=False)
  type = db.StringProperty(multiline=False)
  level = db.StringProperty(multiline=False)
  score = db.IntegerProperty()
  name = db.StringProperty(multiline=False)
  date = db.DateTimeProperty(auto_now_add=True)
  ip = db.StringProperty(multiline=False)

class MainPage(webapp.RequestHandler):
  def get(self):
    template_values = {
      'myText': "Hello World"
      }
    path = os.path.join(os.path.dirname(__file__), 'jewelPairs.html')
    self.response.out.write(template.render(path, template_values))

class HiscoresHandler(webapp.RequestHandler):
  def get(self):
    que = db.Query(Hiscore).order('score')
    que.filter("game =", self.request.get('game'))
    que.filter("type =", self.request.get('type'))
    que.filter("level =", self.request.get('level'))
    hiscores = que.fetch(limit=10)
    template_values = {
      'hiscores': hiscores
      }
    path = os.path.join(os.path.dirname(__file__), 'templates/hiscores.html')
    self.response.out.write(template.render(path, template_values))

class Addhiscore(webapp.RequestHandler):
  def addHiscore(self):
    hiscore = Hiscore()
    hiscore.game = self.request.get('game')
    hiscore.type = self.request.get('type')
    hiscore.level = self.request.get('level')
    hiscore.score = int(self.request.get('score'))
    hiscore.name = self.request.get('name')
    hiscore.ip = self.request.remote_addr
    theKey = hiscore.put()
# new code to find position in table
    que = db.Query(Hiscore).order('score')
    que.filter("game =", self.request.get('game'))
    que.filter("type =", self.request.get('type'))
    que.filter("level =", self.request.get('level'))
    all = que.fetch(maxNum)
    position = None
    count = 0
    while count < maxNum :
      if theKey == all[count].key() :
        position = count
        break
      count = count + 1

    self.response.headers['content-type']  = 'application/json'
    self.response.out.write(simplejson.dumps({'hiscore': True, 'position': position}))


  def post(self):
    # can I change this to only check/read the bottom score?
    que = db.Query(Hiscore).order('score')
    que.filter("game =", self.request.get('game'))
    que.filter("type =", self.request.get('type'))
    que.filter("level =", self.request.get('level'))
    num = que.count()

    if num < maxNum :
      self.addHiscore()
    else :
      all = que.fetch(maxNum)
      if int(self.request.get('score')) < all[maxNum-1].score :
        all[maxNum-1].delete()
        self.addHiscore()
      else :
        self.response.headers['content-type']  = 'application/json'
        self.response.out.write(simplejson.dumps({'hiscore': False, 'position': None}))

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/hiscores', HiscoresHandler),
                                      ('/addhiscore', Addhiscore),
                                      ],
                                     debug=True)

def main():
  run_wsgi_app(application)

maxNum = 10


if __name__ == "__main__":
  main()
